<?php
use think\Session;
use think\Cache;
use app\common\Emodel;
use think\Db;

// 应用公共文件
//获取redis实例
function redis() {
    return Cache::store('redis');
}
//单条记录参数字符转换 gbk to utf8
function findResult($data) {
	$result = [];
    foreach($data as $key => $value){
        $result[iconv('GBK','UTF-8',$key)] = $value;
    }
    return $result;
}
//多条记录参数字符转换 gbk to utf8
function selectResult($data) {
	$list = [];
	foreach($data as $key => $obj){
		$result = [];
		foreach($obj as $key2 => $value){
            if(getfloatlength($value) >= 5) {
                $result[iconv('GBK','UTF-8',$key2)] = round($value,1);
            }
			$result[iconv('GBK','UTF-8',$key2)] = $value;
    	}
    	$list[$key] = $result;
    }
    return $list;
}

function getfloatlength($num){
    if (!is_numeric($num)) {
        return 0;
    }
    $count = 0;
    $temp = explode ( '.', $num );
 
    if (sizeof ( $temp ) > 1) {
        $decimal = end ( $temp );
        $count = strlen ( $decimal );
    }
    return $count;
}

function appUser() {
	return Session::get('appUser');
}

function currTerm() {
    $map = redis()->get("currTerm");
    if(!$map) {
        $result = Db::table("学期名称")
        ->field("ID termId, 学期名称 termName")
        ->order("termId desc")
        ->limit(1)
        ->select();
        foreach($result as $key => $obj){
            $map = $obj;
            $termKey = substr($map["termName"], 0, 4);
            $map["termKey"] = $termKey;
            $map["finishedKey"] = $termKey - 3;
        }
        redis()->set("currTerm", $map);
        //redis()->expire("currTerm", 24*60*60);
    }
    return $map;
}
/**
 * 更新中文表数据
 * $table 中文表名
 * $param 中文参数
 */
function update($table, $param) {
    $set = "";
    $pk = "ID";
    foreach($param as $key => $value) {
        if($key != $pk) {
            $set = $set.$key."='".$value."',";
        }
    }
    $sql = "update ".$table." set ".substr($set, 0, -1)." where ".$pk.'='.$param[$pk];
    $Emodel = new Emodel();
    $Emodel->execute($sql);
}
/**
 * 新增中文表数据
 * $table 中文表名
 * $param 中文参数
 */
function insert($table, $param) {
    $fields = "";
    $values = "";
    foreach ($param as $key => $value) {
        $fields = $fields.$key.",";
        $values = $values."'".$value."',";
    }
    $sql = "insert into ".$table." (".substr($fields, 0, -1).") values(".substr($values, 0, -1).")";
    $Emodel = new Emodel();
    $Emodel->execute($sql);
}
function getDepartName($departIds) {
    $map = redis()->get("orgDepartMap");
    if(!$map) {
        $data = Db::table("t_organize_depart")->where("PARENT_ID = 0")->select();
        foreach($data as $key => $obj){
            $map[$obj["ID"]] = $obj["DEPART"];
        }
        redis()->set("orgDepartMap", $map);
        //redis()->expire("orgDepartMap", 24*60*60);
    }

    $array = explode(",", $departIds);
    $result = [];
    foreach ($array as $value) {
        if(array_key_exists($value, $map)) {
            array_push($result, $map[$value]);
        }
    }
    return implode(",", $result);
}
/**
 * 通过职位ids获取职位名称
 * $positionIds 职位ids
 */
function getPositionName($positionIds) {
    $map = redis()->get("orgPositionMap");
    if(!$map) {
        $data = Db::table("t_organize_depart")->where("PARENT_ID > 0")->select();
        foreach($data as $key => $obj){
            $map[$obj["ID"]] = $obj["POSITION"];
        }
        redis()->set("orgPositionMap", $map);
        redis()->set("orgPositionList", $data);
        //redis()->expire("orgDepartMap", 24*60*60);
    }
    $array = explode(",", $positionIds);
    $result = [];
    foreach ($array as $value) {
        if(array_key_exists($value, $map)) {
            array_push($result, $map[$value]);
        }
    }
    return implode(",", $result);
}
function getPositionMap() {
    $map = redis()->get("orgPositionMap");
    if(!$map) {
        $data = Db::table("t_organize_depart")->where("PARENT_ID > 0")->select();
        foreach($data as $key => $obj){
            $map[$obj["ID"]] = $obj["POSITION"];
        }
        redis()->set("orgPositionMap", $map);
        redis()->set("orgPositionList", $data);
    }
    return $map;
}
function orgPositionList() {
    $map = redis()->get("orgPositionList");
    if(!$map) {
        $data = Db::table("t_organize_depart")->where("PARENT_ID > 0")->select();
        foreach($data as $key => $obj){
            $map[$obj["ID"]] = $obj["POSITION"];
        }
        redis()->set("orgPositionMap", $map);
        redis()->set("orgPositionList", $data);
    }
    return $map;
}
function subjectList() {
    $map = redis()->get("subjectList");
    if(!$map) {
        cacheSubject();
        return redis()->get("subjectList");
        //redis()->expire("subjectList", 24*60*60);
    }
    return $map;
}
function subjectMap() {
    $map = redis()->get("subjectMap");
    if(!$map) {
        cacheSubject();
        return redis()->get("subjectMap");
        //redis()->expire("subjectList", 24*60*60);
    }
    return $map;
}

function cacheSubject() {
    $subjectMap = [];
    $subjectIdMap = [];
    $data = Db::table("学科名称")->field("ID value, 学科名称 text")->select();
    foreach($data as $key => $obj){
        $subjectMap[$obj["value"]] = $obj["text"];
    }
    redis()->set("subjectList", $data);
    redis()->set("subjectMap", $subjectMap);
}
function gradeList() {
    $gradeList = redis()->get("gradeList");
    if(!$gradeList) {
        cacheGrade();
        return redis()->get("gradeList");
    }
    return $gradeList;
}
function gradeMap() {
    $gradeMap = redis()->get("gradeMap");
    if(!$gradeMap) {
        cacheGrade();
        return redis()->get("gradeMap");
    }
    return $gradeMap;
}
function gradeIdMap() {
    $gradeIdMap = redis()->get("gradeIdMap");
    if(!$gradeIdMap) {
        cacheGrade();
        return redis()->get("gradeIdMap");
    }
    return $gradeIdMap;
}
function cacheGrade() {
    $termKey = intval(currTerm()["termKey"]);
    $data = Db::table("年级名称")
    ->field("ID id, 年级名称 grade")
    ->select();
    $gradeMap = [];
    $gradeList = [];
    $gradeIdMap = [];
    foreach($data as $key => $obj){
        $result = [];
        $gradeId = intval($obj["id"]);
        if($gradeId <= 3) {
            $studyType = 1;
            $gradeKey = ($termKey - $gradeId + 1)."_".$studyType;
        }else {
            $studyType = 2;
            $gradeKey = ($termKey - $gradeId + 4)."_".$studyType;;
        }
        $gradeName = $obj["grade"];
        $gradeMap[$gradeKey] = $gradeName;
        $gradeIdMap[$gradeId] = $gradeName;
        $result["text"] = $gradeName;
        $result["value"] = $gradeKey;
        $gradeList[$key] = $result;
    }
    redis()->set("gradeIdMap", $gradeIdMap);
    redis()->set("gradeMap", $gradeMap);
    //redis()->expire("gradeMap", 24*60*60);
    redis()->set("gradeList", $gradeList);
    //redis()->expire("gradeMap", 24*60*60);
}
function getGradeName($grade,$studyType) {
    $map = gradeMap();
    $gradeKey = $grade."_".$studyType;
    if(array_key_exists($gradeKey, $map)) {
        return $map[$gradeKey];
    }
    return "已毕业(".$grade.")级";
}
function getGradeNameByGradeId($gradeId) {
    $map = gradeIdMap();
    return $map[$gradeId];
}
function getGradeByGradeId($gradeId) {
    $gradeId = intval($gradeId);
    $termKey = intval(currTerm()["termKey"]);
    if($gradeId < 3) {
        return $termKey - $gradeId + 1;
    }else {
        return $termKey - $gradeId + 4;
    }
}
function getCommonGradeName($grade,$studyType) {
    $map = gradeMap();
    $gradeKey = $grade."_".$studyType;
    if(array_key_exists($gradeKey, $map)) {
        return $map[$gradeKey];
    }
    return "无";
}
function getSubjectName($subject) {
    $map = subjectMap();
    if(array_key_exists($subject, $map)) {
        return $map[$subject];
    }
    return "";
}
function arrayEq($key, $array){
    if(array_key_exists($key, $array)) {
        return $array[$key];
    }
    return "";
}

// 有选择性的过滤XSS --》 说明：性能非常低-》尽量少用
function removeXSS($data)
{
    require_once './HtmlPurifier/HTMLPurifier.auto.php';
    $_clean_xss_config = HTMLPurifier_Config::createDefault();
    $_clean_xss_config->set('Core.Encoding', 'UTF-8');
    // 设置保留的标签
    $_clean_xss_config->set('HTML.Allowed', 'div,b,strong,i,em,a[href|title],ul,ol,li,p[style],br,span[style],img[width|height|alt|src]');
    $_clean_xss_config->set('CSS.AllowedProperties', 'font,font-size,font-weight,font-style,font-family,text-decoration,padding-left,color,background-color,text-align');
    $_clean_xss_config->set('HTML.TargetBlank', TRUE);
    $_clean_xss_obj = new HTMLPurifier($_clean_xss_config);
    // 执行过滤
    return $_clean_xss_obj->purify($data);
}